home *** CD-ROM | disk | FTP | other *** search
- package com.commerceone.util.string;
-
- public class StringTable {
- static final int DEFAULT_CACHE_SIZE = 1009;
- static final double LOAD_FACTOR = 0.7;
- Bucket[] table;
- Bucket mru;
- int cacheFree;
-
- public StringTable(int cacheSize) {
- this.mru = new Bucket();
- this.table = new Bucket[cacheSize];
- this.cacheFree = (int)((double)this.table.length * 0.7);
- this.mru.nextMru = this.mru;
- this.mru.prevMru = this.mru;
- }
-
- public StringTable() {
- this(1009);
- }
-
- public String convert(char[] buf, int start, int end, boolean permanent) {
- int i = hash(buf, start, end) % this.table.length;
- Bucket bucket = this.table[i];
- if (bucket != null) {
- for(Bucket p = bucket.nextBucket; p != bucket; p = p.nextBucket) {
- if (p.matches(buf, start, end)) {
- if (p.nextMru != null) {
- unlinkMru(p);
- if (permanent) {
- p.nextMru = null;
- } else {
- linkMru(this.mru, p);
- }
- }
-
- return p.string;
- }
- }
- } else {
- bucket = new Bucket();
- bucket.nextBucket = bucket.prevBucket = bucket;
- this.table[i] = bucket;
- }
-
- Bucket tem;
- if (this.cacheFree <= 0) {
- if (this.mru.nextMru == this.mru) {
- for(int j = 0; j < this.table.length; ++j) {
- Bucket h = this.table[j];
- if (h != null) {
- for(Bucket p = h.nextBucket; p != h; p = p.nextBucket) {
- linkMru(this.mru, p);
- }
-
- h.nextBucket = h.prevBucket = h;
- }
- }
- }
-
- tem = this.mru.prevMru;
- unlinkMru(tem);
- tem.prevBucket.nextBucket = tem.nextBucket;
- tem.nextBucket.prevBucket = tem.prevBucket;
- if (permanent) {
- tem.nextMru = null;
- } else {
- linkMru(this.mru, tem);
- }
- } else {
- this.cacheFree += -1;
- tem = new Bucket();
- if (!permanent) {
- linkMru(this.mru, tem);
- }
- }
-
- tem.string = new String(buf, start, end);
- char[] chars = new char[end - start];
- System.arraycopy(buf, start, chars, 0, chars.length);
- tem.chars = chars;
- tem.nextBucket = bucket.nextBucket;
- tem.nextBucket.prevBucket = tem;
- tem.prevBucket = bucket;
- bucket.nextBucket = tem;
- return tem.string;
- }
-
- private static final void unlinkMru(Bucket s) {
- s.prevMru.nextMru = s.nextMru;
- s.nextMru.prevMru = s.prevMru;
- }
-
- private static final int hash(char[] buf, int start, int end) {
- int h;
- for(h = 0; start != end; h += (h << 5) + (buf[start++] & 255)) {
- }
-
- return h & Integer.MAX_VALUE;
- }
-
- private static final void linkMru(Bucket after, Bucket s) {
- s.nextMru = after.nextMru;
- s.nextMru.prevMru = s;
- s.prevMru = after;
- after.nextMru = s;
- }
- }
-